﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Microsoft.Extensions.Options;
using NetTopologySuite.Index.HPRtree;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Net;
using System.Reflection.Metadata;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Interface
{
    public class XM_OrderListInterfaceBusiness : XMInterface_BaseBusiness, IJob_Business, ITransientDependency
    {
        //接口信息
        public Base_InterfaceOption XM_Query;
        public XM_OrderListInterfaceBusiness()
        {
            this.InterfaceName = "XM订单列表";
            //索引字段
            this.MapFields = GetMapField("XM_Query");

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            XM_Query = this.interfaceOption.Where(x => x.OperateType == "XM_Query").First();

            //查询执行前的事件
            this.BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            this.OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //查询执行中的事件
            this.AfterQueryEvent += InterfaceBusiness_AfterQueryEvent;

            //执行非查询请求中的事件
            this.OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="XM_NoQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, XM_NoQueryEventArgs XM_NoQueryEventArgs)
        {
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private async void InterfaceBusiness_BeforeQueryEvent(object sender, XM_QueryEventArgs queryEventArgs)
        {
            try
            {
                //设置请求头参数
                this.SqlDb._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
                var parList = this.SqlDb.GetListBySql<Base_ConfigParameter>(@$"SELECT * FROM  Base_ConfigParameter(NOLOCK) WHERE Code='XiaoMi'");

                queryEventArgs.UrlQuery.Key = parList.Where(x => x.Name == "Key").First().Value;
                queryEventArgs.UrlQuery.AesKey = parList.Where(x => x.Name == "AesKey").First().Value;
                queryEventArgs.UrlQuery.PartnerId = parList.Where(x => x.Name == "PartnerId").First().Value;
                //设置查询第几页
                queryEventArgs.Page.PageIndex = 1;
                //设置查询第几页
                queryEventArgs.Page.PageSize = queryEventArgs.APINodes.Where(x => x.TargetField == "pageSize").First().SourceField.ToInt();
                //查询的总天数
                queryEventArgs.Page.Total = queryEventArgs.APINodes.Where(x => x.TargetField == "beginTime").First().Notes.ToInt();
            }
            catch (Exception ex)
            {

            }


        }

        /// <summary>
        /// 查询中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, XM_QueryEventArgs queryEventArgs)
        {
            try
            {
                //获取请求的数据
                XM_ReqDTO data = new XM_ReqDTO();
                //开始日期需要比上一次的结束日期多出秒，防止重复查询
                var begin = (DateTime.Now.AddDays(-queryEventArgs.Page.Total).Date.ToString("yyyy-MM-dd") + " 00:00:01").ToDateTime();
                //结束日期，开始日期的后7天的日期
                var end = DateTime.Now.AddDays(-queryEventArgs.Page.Total).Date.AddDays(7);
                data.beginTime = new DateTimeOffset(begin).ToUnixTimeSeconds().ToString();//开始日期
                data.endTime = new DateTimeOffset(end).ToUnixTimeSeconds().ToString();//截止日期
                data.pageNo = queryEventArgs.Page.PageIndex;
                string body = GetJsonData(queryEventArgs.APINodes, queryEventArgs.ParentNode, data);

                //获取Sign
                var reqData = JObject.Parse(body);
                //获取所有json节点的信息
                var nodes = queryEventArgs.APINodes.Where(x => x.ParentNO == "TOP" && x.OptionId == XM_Query.Id);
                //需要将请求的数据拼接到url中，先转换成字典
                SortedDictionary<string, object> reqKeyValue = new SortedDictionary<string, object>();
                JObject keyValues = new JObject();
                foreach (var item in nodes)
                {
                    if (!reqData[item.TargetField].ToString().IsNullOrEmpty())
                    {
                        //keyValues.Add(keyValues[item.TargetField].ToString());
                        reqKeyValue.Add(item.TargetField, reqData[item.TargetField]);
                    }
                }

                //
                queryEventArgs.reqData = this.GetBody(reqKeyValue, queryEventArgs.UrlQuery.AesKey, queryEventArgs.UrlQuery.Key, queryEventArgs.UrlQuery.PartnerId);
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 查询执行后的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_AfterQueryEvent(object sender, XM_QueryEventArgs queryEventArgs)
        {

            try
            {
                //将查询后的数据转换成对应格式的数据
                XM_OrderLIst result = (XM_OrderLIst)JsonConvert.DeserializeObject<XM_OrderLIst>(queryEventArgs.ResultStr);
                if (result.code == 0)
                {
                    //XM_OrderLIstDTO_Data DTO_data = (XM_OrderLIstDTO_Data)JsonConvert.DeserializeObject<XM_OrderLIstDTO_Data>(result.biz_content);
                    //查询数量小于单页最大数量,当日数据查询完成
                    if (result.data.orderList.Count < queryEventArgs.Page.PageSize)
                    {


                        //如果所有查询天数小于等于7，查询完成（接口只能查询7天内的数据，如果大于7点的数据需要分批查询）
                        if (queryEventArgs.Page.Total <= 7)
                        {
                            queryEventArgs.Page.Complete = true;
                        }
                        else
                        {
                            //7天分批查询
                            queryEventArgs.Page.Total = queryEventArgs.Page.Total - 7;
                        }
                    }
                    else
                    {
                        //继续查询下一页
                        queryEventArgs.Page.PageIndex++;
                    }
                    queryEventArgs.Rows = result.data.orderList;
                    queryEventArgs.Success = true;
                }
                else
                {
                    queryEventArgs.Success = false;
                }
                //Thread.Sleep(20000);
            }
            catch (Exception ex)
            {
                queryEventArgs.Success = false;
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
                Thread.Sleep(10000);
            }

        }

        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {
            List<XM_OrderLIst.OrderList> QQ = await this.QueryAsync<XM_OrderLIst.OrderList>(this.XM_Query, SqlDb);
        }


        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
